var express = require('express');
var router = express.Router();

const { Keyring } = require('@polkadot/keyring');
const { WsProvider, ApiPromise, SignerOptions} = require('@polkadot/api');


/**
 * 通过私钥种子获取地址
 */
router.post('/address', function(req, res) {
    // 获取传参
    const params = req.body;
    // 设置计算地址方式
    const keyring = new Keyring({ type: 'sr25519' });
    // 设置地址前缀
    keyring.setSS58Format(params.prefix);
    res.set('Content-Type', 'application/json');
    res.send('{\"result\":\"' + keyring.addFromUri(params.privateKey).address + '\"}');
});

/**
 * 判断地址是否正确
 * 这里只做地址校验不做地址前缀校验，如需校验前缀则将地址base58 decode 然后校验数组的第一个值
 */
router.get('/validateAddress/:address', function (req, res) {
    const params = req.params;
    res.set('Content-Type', 'application/json');
    try {
        const keyring = new Keyring();
        keyring.addFromAddress(params.address);
        res.status(200).send('{\"result\":true}');
    } catch (e) {
        console.log(e);
        res.status(200).send('{\"result\":false, \"error\":\"' + e.message + '\"}');
    }
});

/**
 * 交易签名
 */
router.post('/sign', function (req, res) {
    const params = req.body;
    sign(params.to, params.value, params.privateKey).then((tx) => {
        res.set('Content-Type', 'application/json');
        res.status(200).send('{\"result\":\"' + tx.toHex() + '\"}');
    });
});

/**
 * 异步签名
 *
 * @param to    目标地址
 * @param value 金额
 * @param privateKey    私钥种子
 * @returns {Promise<ApiType extends ApiTypes>}
 */
async function sign(to, value, privateKey) {
    // Initialise the provider to connect to the local node
    // ws://47.245.8.129:9944
    const api = await getApi();

    const transfer = api.tx.balances.transfer(to, value);

    const keyring = new Keyring({ type: 'sr25519' });
    // 设置地址前缀
    const from = keyring.addFromUri(privateKey);

    return await transfer.signAsync(from, {era: 30});
}

var api;

async function getApi() {
    // Create the API and wait until ready
    if (api === undefined) {
        console.log('Create the API and wait until ready');
        console.log('Initialise the provider to connect to the local node');
        const provider = new WsProvider("ws://127.0.0.1:9944");
        api = await ApiPromise.create({ provider });
        const [chain, nodeName, nodeVersion] = await Promise.all([
            api.rpc.system.chain(),
            api.rpc.system.name(),
            api.rpc.system.version(),
        ]);

        console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`);
    }
    return api;
}

getApi();

module.exports = router;
